package com.sky.edumanageapi.user.service.impl;

import com.sky.edumanageapi.base.exception.ServiceException;
import com.sky.edumanageapi.base.response.StatusCode;
import com.sky.edumanageapi.user.dao.mapper.UserMapper;
import com.sky.edumanageapi.user.dao.repository.UserRepository;
import com.sky.edumanageapi.user.pojo.dto.UserLogin;
import com.sky.edumanageapi.user.pojo.dto.UserRegister;
import com.sky.edumanageapi.user.pojo.po.UserPO;
import com.sky.edumanageapi.user.pojo.vo.UserVO;
import com.sky.edumanageapi.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public void SaveUser(UserRegister userRegister) {
        log.debug("用户注册Service传入参数:{}", userRegister);

        UserPO userPO = new UserPO();
        BeanUtils.copyProperties(userRegister,userPO);
        if(userPO.getUserId()== null) {//新增
            if (userRepository.getUserByUsername(userRegister.getUsername()) != null) {
                throw new ServiceException(StatusCode.USERNAME_ALREADY_EXISTS);
            }
            userPO.setCreateTime(new Date());
            userPO.setStatus(1);
            log.debug("用户注册Mapper传入参数:{}", userPO);
            userRepository.insert(userPO);
        }else {
            userPO.setUpdateTime(new Date());
            userRepository.updateUser(userPO);
        }

    }

    @Override
    public UserVO login(UserLogin userLogin) {
        log.debug("用户登录Service传入参数:{}", userLogin);
        UserPO userPO = userRepository.getUserByUsername(userLogin.getUsername());
        if (userPO == null) {
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if (!userPO.getPassword().equals(userLogin.getPassword())) {
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userPO,userVO);
        return userVO;
    }

    @Override
    public UserVO info(Integer id) {
        UserPO userPO=userRepository.getUserById(id);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userPO,userVO);
        return userVO;
    }
}
